//
//  BossMessagVC.m
//  LazyCat
//
//  Created by jike on 16/3/23.
//  Copyright (c) 2016年 zhanshu. All rights reserved.
//

#import "BossMessagVC.h"
#import "AFNetworkHandler.h"
#import "MessShowView.h"
#import "LoginViewController.h"
#import "MJChiBaoZiHeader.h"
#import "MJDIYBackFooter.h"
#import "FeWifiManHub.h"
#import "BossMessageCell.h"
#import "OrderViewController.h"
#import "html5MYViewController.h"
#import "ALView+PureLayout.h"
#import "MJDIYHeader.h"
@interface BossMessagVC ()<UITableViewDataSource,UITableViewDelegate,UIScrollViewDelegate>

@end

@implementation BossMessagVC
{
    UITableView *_tableView;
    UIView *_lineView;
    UIView *_bgView;
    NSMutableArray *_dataArray;//数据源
    BOOL _isLoading;
    NSString *_urlIndex;//接口起始页
    NSString *_totalCount;//总页数
    UIView *_backTView;
    FeWifiManHub *_loading;//加载框
    NSInteger _heightCell;//cell高度
    NSArray *_newArr;//新加载的数据
    NSInteger _inViewH;//进入view的高度。
}
- (void)viewWillAppear:(BOOL)animated {
    [super viewWillAppear:animated];
    [self scrollToBottom:NO];
}
-(void)initNav:(NSString*)title doBack:(BOOL)doBack {
    self.navBar.hidden=NO;
    self.titleLable.text=title;
    self.titleLable.textColor = [UIColor whiteColor];
    if (doBack) {
        self.backBtn=[UIButton buttonWithType:UIButtonTypeCustom];
        self.backBtn.frame=CGRectMake(8, 20+(44-21)/2, 12, 21);
        [self.backBtn setNormalImageWith:@"lALOCzPrgiYW_22_38"];
        [self.backBtn addTarget:self action:@selector(backAction:) forControlEvents:UIControlEventTouchUpInside];
        [self.backBtn setHitTestEdgeInsets:UIEdgeInsetsMake(-10, -14, -14, -25)];
        [self.navBar addSubview:self.backBtn];
    }
}
-(void)backAction:(UIButton *)sender {
    [self.navigationController popViewControllerAnimated:YES];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    [self createUI];
    [self getData];
}
//改变状态栏颜色为白色
- (UIStatusBarStyle)preferredStatusBarStyle{
    return UIStatusBarStyleLightContent;
}
- (void)createUI {
    _totalCount = @"";
    self.automaticallyAdjustsScrollViewInsets = NO;
    self.view.backgroundColor = BackColor;
    [self initNav:@"消息中心" doBack:YES];
    self.navBar.backgroundColor = SetColor(0, 140, 206, 1);
    UIView *lineV = [[UIView alloc]initWithFrame:CGRectMake(0, 63, ScreenWidth, 1)];
    lineV.backgroundColor = [UIColor lightGrayColor];
    lineV.alpha = 0.2;
    [self.view addSubview:lineV];
    _tableView = [[UITableView alloc]initWithFrame:CGRectMake(0, 64, ScreenWidth, ScreenHeight - 64) style:UITableViewStyleGrouped];
    _tableView.delegate = self;
    _tableView.dataSource = self;
    _tableView.showsVerticalScrollIndicator = NO;
    //_tableView.transform = CGAffineTransformMakeRotation(-M_PI);
    _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
    [self.view addSubview:_tableView];
//    MJChiBaoZiFooter *footer = [MJChiBaoZiFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
//    footer.refreshingTitleHidden = YES;
    MJDIYHeader *header = [MJDIYHeader headerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    header.label.hidden = YES;
    _tableView.header = header;
    
    //_tableView.footer = [MJDIYBackFooter footerWithRefreshingTarget:self refreshingAction:@selector(loadMore)];
    // 设置footer
    //_tableView.footer = footer;
    _isLoading = NO;
    _urlIndex = @"1";
    _backTView = [[UIView alloc]initWithFrame:CGRectMake(0, 0, ScreenWidth, ScreenHeight - 64)];
    _backTView.backgroundColor = BackColor;
    _backTView.hidden = YES;
    //_backTView.transform = CGAffineTransformMakeRotation(-M_PI);
    [_tableView addSubview:_backTView];
    UIImageView *backImage = [[UIImageView alloc]initWithFrame:CGRectMake((ScreenWidth - 80)/2, 100, 80, 90)];
    backImage.image = [UIImage imageNamed:@"noMessage"];
    [_backTView addSubview:backImage];
    UILabel *label = [[UILabel alloc]initWithFrame:CGRectMake((ScreenWidth - 200)/2, backImage.frame.origin.y + 90, 200, 50)];
    label.textColor = SetColor(153, 153, 153, 1);
    label.textAlignment = NSTextAlignmentCenter;
    label.text = @"暂无相关消息";
    [_backTView addSubview:label];
    _dataArray = [[NSMutableArray alloc]init];
    _loading = [[FeWifiManHub alloc] initWithView:self.view withMode:FeWifiManHubModeOnlyLoader];
    _loading.frame = CGRectMake(_loading.frame.origin.x, _loading.frame.origin.y - 64, _loading.frame.size.width, _loading.frame.size.height);
    [_tableView addSubview:_loading];
   
    [_loading show];
}
- (void)loadMore {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    if ([_urlIndex intValue] > [_totalCount intValue]) {
        [[MessShowView share]showWithMess:@"没有更多数据"];
        [_tableView.header endRefreshing];
        return ;
    }
    _urlIndex = [NSString stringWithFormat:@"%d",[_urlIndex intValue]+1];
    [self getData];
}
-(void)getData {
    NSString *url = [NSString stringWithFormat:xiaoxiUrl,[AppData share].username,_urlIndex,@"15"];
    if ([_urlIndex isEqualToString:@"1"]) {
        [_dataArray removeAllObjects];
    }
    [AFNetworkHandler GETWithAFNByURL:url completion:^(id result) {
        NSDictionary *allDic = result;
        _totalCount = [NSString stringWithFormat:@"%@",[allDic objectForKey:@"totalpage"]];
        NSLog(@"%@",_totalCount);
        if ([allDic[@"r"] isEqualToString:@"T"]) {
            _newArr = [allDic objectForKey:@"d"];
//            NSMutableArray *arr = [[NSMutableArray alloc]init];
//            
//            for (int i = 0; i < _newArr.count; i++) {
//                [arr addObject:_newArr[_newArr.count-1 -i]];
//            }
                //[_dataArray addObjectsFromArray:_newArr];
            //倒叙后刷新数据后要倒置数据源
            for (int i = 0; i < _newArr.count; i++) {
                [_dataArray insertObject:_newArr[_newArr.count - 1-i] atIndex:0];
            }
        }
        [_tableView.header endRefreshing];
        [_loading dismiss];
        [_loading removeFromSuperview];
        if ([_totalCount isEqualToString:@"0"]||_totalCount == nil||[_totalCount isEqualToString:@""]) {
            _backTView.hidden = NO;
        }else {
            _backTView.hidden = YES;
        }
        [_tableView reloadData];
        [self scrollToBottom:NO];
        _isLoading = NO;
    }];
    [_tableView.header endRefreshing];
    if (kNetworkNotReachability) {
        _backTView.hidden = NO;
        //[_tableView.header endRefreshing];
        [_tableView.footer endRefreshing];
        [_loading dismiss];
        [_loading removeFromSuperview];
    }else {
        _backTView.hidden = YES;
    }
}
- (void)addRefresh {
    if (_isLoading) {
        return;
    }
    _isLoading = YES;
    //    MJChiBaoZiHeader *header = [MJChiBaoZiHeader headerWithRefreshingBlock:^{
    _urlIndex = @"1";
    //        [header beginRefreshing];
    [self getData];
    //    }];
    //    _tableView.header = header;
    //    header.lastUpdatedTimeLabel.hidden = YES;
}
-(void)scrollToBottom:(BOOL)animated
{    //让其滚动到底部
    dispatch_async(dispatch_get_main_queue(), ^
                   {
                       NSInteger row = _newArr.count;
                       if (row >= 1)
                       {
                           [_tableView scrollToRowAtIndexPath:[NSIndexPath indexPathForRow:row-1 inSection:0] atScrollPosition:UITableViewScrollPositionBottom animated:animated];
                       }
                   });
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath {
    BossMessageCell *cell = [tableView dequeueReusableCellWithIdentifier:@"bossmessage"];
    if (cell == nil) {
        cell = [[NSBundle mainBundle]loadNibNamed:@"BossMessageCell" owner:self options:nil][0];
    }
    /**
     *  每次清空之前创建的cell上得label
     */
    for (UIView * view in cell.contentView.subviews) {
        if (view.tag == 111) {
            [view removeFromSuperview];
        }
    }
    //
    cell.selectionStyle = UITableViewCellSelectionStyleNone;
    NSString *inType;
    CGSize size;
    NSString *contentStr;
    NSArray *arr;
    if (indexPath.row < [_dataArray count]) {
    cell.titleLabel.text = [_dataArray[indexPath.row] objectForKey:@"title"];
    cell.timeLabel.text = [_dataArray[indexPath.row] objectForKey:@"time"];
    cell.subTimeLabel.text = [_dataArray[indexPath.row] objectForKey:@"time"];
    arr = (NSArray *)[_dataArray[indexPath.row] objectForKey:@"models"];
    cell.arr = arr;
    contentStr = [_dataArray[indexPath.row] objectForKey:@"context"];;
    cell.contentStr = contentStr;
    size = CGSizeMake(ScreenWidth-60, 1000);
    inType = [_dataArray[indexPath.row] objectForKey:@"opentype"];
    cell.inType = inType;
    }
    CGSize labelSize = [contentStr sizeWithFont:[UIFont systemFontOfSize:15] constrainedToSize:size lineBreakMode:NSLineBreakByClipping];
    
    if ([inType isEqualToString:@"1"] || [inType isEqualToString:@"2"] || [inType isEqualToString:@"5"]) {
        _inViewH = 0;
    }else {
        _inViewH = -20;
    }
    cell.contentView.backgroundColor = SetColor(245, 245, 249, 1);
    _heightCell = 140 +10 +35 + arr.count * 23 - 15 + 10 + labelSize.height + _inViewH;
    CGRect rect = cell.frame;
    rect.size.height = _heightCell;
    cell.frame = rect;
    //cell.transform = CGAffineTransformMakeRotation(-M_PI);
    return cell;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section {
    return  _dataArray.count;
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath {
//    NSInteger count = [[_dataArray[indexPath.row] objectForKey:@"models"] count];
//    
//    return 140 +10 +35 + count * 23;
    return _heightCell + _inViewH;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath {
    if(tableView.tag == 0){
        if (indexPath.row < _dataArray.count) {
            
//            NSDictionary *dict = _dataArray[indexPath.row];
//            Html5ViewController *html5VC = [[Html5ViewController alloc]init];
//            NSString *strUrl = [NSString stringWithFormat:detailMessage,[AppData share].username,dict[@"id"],[Utils md5SignStr]];
//            html5VC.requestUrl = strUrl;
//            if ([[_dataArray[indexPath.row] objectForKey:@"noticetype"]isEqualToString:@"0"]) {
//                html5VC.titleStr = @"系统消息";
//            }else {
//                html5VC.titleStr = @"主题消息";
//            }
//            //html5VC.relod = @"yes";
            NSString *type = [_dataArray[indexPath.row] objectForKey:@"opentype"];
            
            if ([type isEqualToString:@"1"]) {
                
                OrderViewController *orderVC = [[OrderViewController alloc] init];
                orderVC.orderDate = @"";
                [self.navigationController pushViewController:orderVC animated:YES];
            }else if ([type isEqualToString:@"2"]){
                OrderViewController *orderVC = [[OrderViewController alloc] init];
                orderVC.tuiHuoManager = YES;
                [self.navigationController pushViewController:orderVC animated:YES];
            }else if ([type isEqualToString:@"5"]){
                html5MYViewController *htmlVC = [[html5MYViewController alloc]init];
                [self.navigationController pushViewController:htmlVC animated:YES];
            }
            
        }
    }
}
- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section {
    return 0.0001;
}
- (CGFloat)tableView:(UITableView *)tableView heightForFooterInSection:(NSInteger)section {
    return 0.0001;
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    
}
@end
